package com.example.demo.controller;

import com.example.demo.mapper.OrgMapper;
import com.example.demo.service.InsertData;
import org.apache.hc.core5.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
public class DataController {
    private static final Logger logger = LoggerFactory.getLogger(DataController.class);

    @Autowired
    InsertData insertData;

    @Autowired
    OrgMapper orgMapper;

    @GetMapping("/data")
    public String getData() {
        // 处理获取数据的逻辑
        return "data/data"; // 返回数据页面的视图名称
    }

    @GetMapping("/insertData")
    @ResponseBody
    public String insertData(
            @RequestParam("date") String date,
            @RequestParam("names") List<String> names,
            @RequestParam("isAudit") String isAudit,
            @RequestParam("isSend") String isSend) throws URISyntaxException, IOException, ParseException {
        logger.info("收到插入数据请求，日期：{}，名称列表：{}，是否审核：{}，是否上传：{}", date, names, isAudit, isSend);
        try {
            for (String name : names) {
                Integer orgId = orgMapper.getOrgIdByOrgName(name);
                int i = insertData.insertDieChicken(date, name, isAudit, isSend, orgId);
                logger.info("插入数据成功，名称：{}，组织 ID：{}，影响行数：{}", name, orgId, i);
            }
            return "请求已接收，参数处理成功";
        } catch (Exception e) {
            logger.error("插入数据失败，日期：{}，名称列表：{}，是否审核：{}，是否上传：{}", date, names, isAudit, isSend, e);
            return "插入数据失败，请稍后重试";
        }
    }
}
